import React, { useEffect } from 'react';
import { Form, Input, DatePicker, InputNumber, Button, Card, message, Space } from 'antd';
import { useDispatch, useSelector } from 'react-redux';
import { useNavigate, useParams } from 'react-router-dom';
import { fetchFlightById, createFlight, updateFlight, clearCurrentFlight } from '../../store/slices/flightSlice';
import dayjs from 'dayjs';




const FlightForm = () => {
  const [form] = Form.useForm();
  const dispatch = useDispatch();
  const navigate = useNavigate();
  const { id } = useParams();
  const { currentFlight, loading } = useSelector((state) => state.flights);
  const isEdit = Boolean(id);

  useEffect(() => {
    if (isEdit) {
      dispatch(fetchFlightById(id));
    }
    return () => {
      dispatch(clearCurrentFlight());
    };
  }, [dispatch, id, isEdit]);

  useEffect(() => {
    if (currentFlight && isEdit) {
      form.setFieldsValue({
        ...currentFlight,
        departure_time: currentFlight.departure_time ? dayjs(currentFlight.departure_time) : null,
        arrival_time: currentFlight.arrival_time ? dayjs(currentFlight.arrival_time) : null,
      });
    }
  }, [currentFlight, form, isEdit]);

  const handleSubmit = async (values) => {
    try {
      const formattedValues = {
        ...values,
        departure_time: values.departure_time ? values.departure_time.toISOString() : null,
        arrival_time: values.arrival_time ? values.arrival_time.toISOString() : null,
      };

      if (isEdit) {
        await dispatch(updateFlight({ id, data: formattedValues })).unwrap();
        message.success('航班更新成功');
      } else {
        await dispatch(createFlight(formattedValues)).unwrap();
        message.success('航班创建成功');
      }
      navigate('/flights');
    } catch (error) {
      message.error(isEdit ? '更新失败: ' + error.message : '创建失败: ' + error.message);
    }
  };

  const handleCancel = () => {
    navigate('/flights');
  };

  return (
    <Card
      title={isEdit ? '编辑航班' : '创建航班'}
      style={{ maxWidth: 800, margin: '0 auto' }}
    >
      <Form
        form={form}
        layout="vertical"
        onFinish={handleSubmit}
        initialValues={{
          status: 'scheduled',
          total_seats: 200,
          available_seats: 200,
        }}
      >
        <Form.Item
          label="航班号"
          name="flight_number"
          rules={[{ required: true, message: '请输入航班号' }]}
        >
          <Input placeholder="例如: CA1234" />
        </Form.Item>

        <Form.Item
          label="航空公司"
          name="airline"
          rules={[{ required: true, message: '请输入航空公司' }]}
        >
          <Input placeholder="例如: 中国国际航空" />
        </Form.Item>

        <Form.Item
          label="出发城市"
          name="departure_city"
          rules={[{ required: true, message: '请输入出发城市' }]}
        >
          <Input placeholder="例如: 北京" />
        </Form.Item>

        <Form.Item
          label="到达城市"
          name="arrival_city"
          rules={[{ required: true, message: '请输入到达城市' }]}
        >
          <Input placeholder="例如: 上海" />
        </Form.Item>

        <Form.Item
          label="出发机场"
          name="departure_airport"
          rules={[{ required: true, message: '请输入出发机场' }]}
        >
          <Input placeholder="例如: 北京首都国际机场" />
        </Form.Item>

        <Form.Item
          label="到达机场"
          name="arrival_airport"
          rules={[{ required: true, message: '请输入到达机场' }]}
        >
          <Input placeholder="例如: 上海浦东国际机场" />
        </Form.Item>

        <Form.Item
          label="出发时间"
          name="departure_time"
          rules={[{ required: true, message: '请选择出发时间' }]}
        >
          <DatePicker
            showTime
            format="YYYY-MM-DD HH:mm:ss"
            style={{ width: '100%' }}
            placeholder="选择出发时间"
          />
        </Form.Item>

        <Form.Item
          label="到达时间"
          name="arrival_time"
          rules={[{ required: true, message: '请选择到达时间' }]}
        >
          <DatePicker
            showTime
            format="YYYY-MM-DD HH:mm:ss"
            style={{ width: '100%' }}
            placeholder="选择到达时间"
          />
        </Form.Item>

        <Form.Item
          label="价格"
          name="price"
          rules={[{ required: true, message: '请输入价格' }]}
        >
          <InputNumber
            min={0}
            precision={2}
            style={{ width: '100%' }}
            placeholder="请输入价格"
            addonBefore="¥"
          />
        </Form.Item>

        <Form.Item
          label="总座位数"
          name="total_seats"
          rules={[{ required: true, message: '请输入总座位数' }]}
        >
          <InputNumber
            min={1}
            max={1000}
            style={{ width: '100%' }}
            placeholder="请输入总座位数"
          />
        </Form.Item>

        <Form.Item
          label="可用座位数"
          name="available_seats"
          rules={[{ required: true, message: '请输入可用座位数' }]}
        >
          <InputNumber
            min={0}
            max={1000}
            style={{ width: '100%' }}
            placeholder="请输入可用座位数"
          />
        </Form.Item>

        <Form.Item>
          <Space>
            <Button type="primary" htmlType="submit" loading={loading}>
              {isEdit ? '更新航班' : '创建航班'}
            </Button>
            <Button onClick={handleCancel}>
              取消
            </Button>
          </Space>
        </Form.Item>
      </Form>
    </Card>
  );
};

export default FlightForm;